﻿using System.Reactive.Disposables;
using System.Reactive.Linq;
using AntDesign;
using Blazor.CoffeeTalesApi.Entity;
using Blazor.Core;
using Blazor.Core.Extensions;
using Blazor.Pages.UpdateSetting.Modals.ChangeJumpUrl;
using Blazor.Pages.UpdateSetting.Modals.ChangeNativeVersion;
using Blazor.ViewModels.UpdateSetting;
using ReactiveUI;

namespace Blazor.Views.UpdateSetting;

public partial class UpdateSetting : SoraniComponentBase<UpdateSettingViewModel>
{
    private ILogger _logger;

    public UpdateSetting(UpdateSettingViewModel viewModel, ILogger<UpdateSetting> logger)
    {
        ViewModel = viewModel;
        _logger = logger;
    }

    protected override void BindWithViewModel(UpdateSettingViewModel viewModel, CompositeDisposable disposable)
    {
        viewModel.ChangeNativeVersionInteraction
            .RegisterHandler(ChangeNativeVersionInteractionHandler)
            .DisposeWith(disposable);

        viewModel.ChangeJumpUrlInteraction
            .RegisterHandler(ChangeJumpUrlInteractionHandler)
            .DisposeWith(disposable);
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        await ViewModel!.SelectChannel.Execute(Channel.ForceLogin);
    }

    private async Task ChannelClickHandler(MenuItem menuItem)
    {
        var key = menuItem.Key;

        if (key is null)
        {
            throw new ArgumentNullException(nameof(key));
        }

        if (!Enum.TryParse<Channel>(key, out var channel))
        {
            throw new ArgumentException(nameof(key));
        }

        await ViewModel!.SelectChannel.Execute(channel);
        await ViewModel!.Refresh.Execute();
    }

    private async Task ChangeNativeVersionInteractionHandler(
        IInteractionContext<ChangeNativeVersionOptions, ChangeNativeVersionResult?> interactionContext)
    {
        var result =
            await ModalService
                .OpenCustomModal<ChangeNativeVersionModal, ChangeNativeVersionOptions, ChangeNativeVersionResult?>(
                    interactionContext.Input);

        interactionContext.SetOutput(result);
    }
    
    private async Task ChangeJumpUrlInteractionHandler(IInteractionContext<string, Uri?> context)
    {
        var result = await ModalService.OpenCustomModal<ChangeJumpUrlModal, string, Uri?>(context.Input);
        context.SetOutput(result);
    }
}